package com.yifeng.repo.micro.service.client.configure;

import feign.Logger;
import feign.Request;
import feign.Retryer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * Created by daibing on 2022/8/6.
 */
@Configuration
@EnableConfigurationProperties(MicroServiceClientProperties.class)
@ConditionalOnClass({MicroServiceClientProperties.class})
@ConditionalOnProperty(prefix = "yfcloud.micro-service.client", name = "enabled", matchIfMissing = true)
public class MicroServiceClientConfiguration {
    private final MicroServiceClientProperties properties;

    public MicroServiceClientConfiguration(MicroServiceClientProperties properties) {
        this.properties = properties;
    }

    @Bean
    public Logger.Level loggerLevel() {
        switch (properties.getFeignLogLevel()) {
            case "NONE":
                return Logger.Level.NONE;
            case "BASIE":
                return Logger.Level.BASIC;
            case "HEADERS":
                return Logger.Level.HEADERS;
            case "FULL":
                return Logger.Level.FULL;
        }
        return Logger.Level.BASIC;
    }

    @Bean
    public Request.Options requestOptions() {
        return new Request.Options(properties.getConnectTimeout(), TimeUnit.MILLISECONDS, properties.getReadTimeout(), TimeUnit.MILLISECONDS, true);
    }

    @Bean
    public Retryer retryer() {
        if (properties.isRetry()) {
            return new Retryer.Default(properties.getRetryPeriod(), properties.getRetryMaxPeriod(), properties.getRetryMaxAttempts());
        } else {
            return Retryer.NEVER_RETRY;
        }
    }

    // TODO: 需要通过configuration的方式引入httpclient
}
